/*
 * @Author: zhengzhuang
 * @since: 2020-01-09 11:29:03
 * @lastTime     : 2020-01-13 11:53:01
 * @LastAuthor   : zhengzhuang
 * @文件相对于项目的路径: /wangyueche_driver/lib/pages/carpool_page/carpool_fellow_passengers.dart
 * @message: 顺风车同行乘客 CarpoolFellowPassengers
 */
import 'dart:async';

import 'package:C20Driver/model/carpool_passenger_order_info.dart';
import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/provider/order_information.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:C20Driver/utils/utils.dart';
import 'package:C20Driver/widget/no_data_widget.dart';
import 'package:C20Driver/widget/spinkit.dart';
import 'package:provider/provider.dart';
import 'package:C20Driver/event/event_bus.dart';

class CarpoolFellowPassengers extends StatefulWidget {
  final String id;
  CarpoolFellowPassengers({this.id});
  @override
  _CarpoolFellowPassengersState createState() =>
      _CarpoolFellowPassengersState();
}

class _CarpoolFellowPassengersState extends State<CarpoolFellowPassengers> {
  bool _showResult = true;
  bool isFinish = false;
  Timer _tenTimer;
  var tenMinute = 60 * 10;
  @override
  void initState() {
    super.initState();
    eventBus.on<RefreshCarpoolPassengers>().listen((event) {
      if (event.state == 1) {
        setState(() {
          tenMinute = 60 * 10;
          _showResult = true;
        });
        if (_tenTimer == null) {
          _startTimer();
        }
      } else {
        isFinish = true;
        setState(() {
          isFinish = true;
        });
      }
    });
    _startTimer();
  }

  _startTimer() {
    if (_tenTimer == null) {
      _tenTimer = new Timer.periodic(new Duration(seconds: 5), (timer) {
        if (tenMinute > 0) {
          setState(() {
            _showResult = true;
            tenMinute -= 1;
          });
        } else {
          _tenTimer.cancel();
          _tenTimer = null;
        }
      });
    }
  }

  /// 取消订单
  _refuseFreeRideOrder(info) {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        content: Text('您确认要拒绝该乘客吗？'),
        actions: <Widget>[
          FlatButton(
            child: Text('确认取消订单'),
            onPressed: () {
              NavigatorUtil.goBack(context);
              Request.refuseFreeRideOrder(context, info);
            },
          ),
          FlatButton(
            child: Text('取消'),
            onPressed: () {
              NavigatorUtil.goBack(context);
            },
          ),
        ],
      ),
    );
  }

  /// 订单完成
  void _orderFulfillment(String id) {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('行程完成'),
          content: Text('请确认是否送完所有乘客?'),
          actions: <Widget>[
            FlatButton(
              child: Text('行程完成'),
              onPressed: () async {
                Navigator.of(context).pop();
                bool back = await Request.orderFulfillment(context, id);
                _tenTimer.cancel();
                _tenTimer = null;
                if (back) {
                  isFinish = true;
                  Provider.of<OrderInformation>(context, listen: false)
                      .cleanCarpoolLocalInfo();
                }
              },
            ),
            FlatButton(
              child: Text('还没有'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future _getFreeRidePeerOrdersFun() async {
    return await Request.getFreeRidePeerOrdersFun(widget.id);
  }

  @override
  Widget build(BuildContext context) {
    OrderInformation provider =
        Provider.of<OrderInformation>(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        elevation: 0,
        leading: GestureDetector(
          onTap: () {
            if (isFinish) {
              NavigatorUtil.goToHomeRemovePage(context);
              eventBus.fire(new MyEvent('1'));
            } else {
              Navigator.of(context).pop();
            }
          },
          child: Icon(
            Icons.arrow_back_ios_outlined,
            color: Color(0xff000000),
          ),
        ),
      ),
      body: Container(
        color: Color(0xffffffff),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.only(
                    left: ScreenUtil().setWidth(30),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        width: ScreenUtil().setWidth(8),
                        height: ScreenUtil().setWidth(28),
                        decoration: BoxDecoration(
                          color: Color(0xff3FB956),
                          borderRadius: BorderRadius.all(
                            Radius.circular(
                              ScreenUtil().setWidth(4),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: ScreenUtil().setWidth(12),
                      ),
                      Text(
                        isFinish ? '行程结束' : '订单进行中',
                        textAlign: TextAlign.left,
                        style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: ScreenUtil().setWidth(32),
                            fontWeight: FontWeight.w500),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: ScreenUtil().setWidth(20),
                ),
                Padding(
                  padding: EdgeInsets.only(
                    left: ScreenUtil().setWidth(30),
                  ),
                  child: Text(
                    isFinish ? '乘车费用已到账，请前往钱包余额查看' : '请注意用车时间并及时出发接送乘客',
                    style: TextStyle(
                      color: Color(0xff999999),
                      fontSize: ScreenUtil().setWidth(28),
                    ),
                  ),
                ),
                SizedBox(
                  height: ScreenUtil().setWidth(20),
                ),
              ],
            ),
            Expanded(
              child: RefreshIndicator(
                onRefresh: () async {
                  setState(() {
                    _showResult = true;
                  });
                },
                child: FutureBuilder(
                  future: _showResult ? _getFreeRidePeerOrdersFun() : null,
                  builder: (BuildContext context, AsyncSnapshot snapshot) {
                    if (snapshot.hasData) {
                      List dataInfo = snapshot.data;
                      for (var i = 0; i < dataInfo.length; i++) {
                        var json = dataInfo[i];
                        print("getFreeRidePeerOrders=====" + json.toString());
                      }
                      if (dataInfo.length != 0) {
                        return ListView.builder(
                          itemCount: dataInfo.length,
                          itemBuilder: (BuildContext context, index) {
                            return _listCard(context, dataInfo[index]);
                          },
                        );
                      } else {
                        return NoDataWidget();
                      }
                    } else {
                      return NoDataWidget();
                    }
                  },
                ),
              ),
            ),
            Container(
              width: ScreenUtil().setWidth(750.0),
              height: ScreenUtil().setWidth(156),
              decoration: BoxDecoration(
                color: Color(0xffffffff),
                boxShadow: <BoxShadow>[
                  BoxShadow(
                    color: Color(0xffeeeeee),
                    blurRadius: 10,
                    offset: Offset(0, -5),
                  )
                ],
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Container(
                    width: ScreenUtil().setWidth(352.0),
                    height: ScreenUtil().setWidth(100.0),
                    decoration: BoxDecoration(
                        color: isFinish ? Color(0x22EC674A) : Color(0xffEEF6EE),
                        borderRadius: BorderRadius.all(
                            Radius.circular(ScreenUtil().setWidth(50)))),
                    child: MaterialButton(
                      textColor:
                          isFinish ? Color(0xffEC674A) : Color(0xff668D6E),
                      child: Text(
                        isFinish ? '110 报警' : '可拼乘客',
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(30),
                            fontWeight: FontWeight.w500),
                      ),
                      onPressed: () {
                        if (isFinish) {
                          Utils.callPhone('110');
                        } else {
                          NavigatorUtil.jump(context,
                              '/generateWindmillTrip?id=${provider.carpoolOrderInfo.orderId}&start=0010');
                        }
                      },
                    ),
                  ),
                  Container(
                    width: ScreenUtil().setWidth(352.0),
                    height: ScreenUtil().setWidth(100.0),
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                          colors: [
                            Color(0xff3FB956),
                            Color(0xff65CA00),
                          ],
                        ),
                        borderRadius: BorderRadius.all(
                            Radius.circular(ScreenUtil().setWidth(50)))),
                    child: MaterialButton(
                      textColor: Colors.white,
                      child: Text(
                        isFinish ? '联系客服' : '订单完成',
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(30),
                            fontWeight: FontWeight.w500),
                      ),
                      onPressed: () {
                        if (isFinish) {
                          Utils.callPhone('400-089-3089');
                        } else {
                          _orderFulfillment(provider.carpoolOrderInfo.orderId);
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 列表卡片
  Widget _listCard(context, dataIndex) {
    String typeStr = '';

    if (isFinish) {
      if (dataIndex['ride_type'] == '0010') {
        typeStr = '拼车';
      } else {
        typeStr = '独享';
      }
    } else {
      if (dataIndex['status'] == '0000') {
        typeStr = '订单完成';
      } else if (dataIndex['pay_state'] == '0000') {
        typeStr = '已付款';
      } else if (dataIndex['pay_state'] == '0010') {
        typeStr = '未付款';
      }
    }

    String passStyeStr = '';
    if (dataIndex['status'] == '0020') {
      passStyeStr = '去送乘客';
    } else {
      passStyeStr = '去接乘客';
    }
    return Container(
      width: ScreenUtil().setWidth(750.0),
      // height: ScreenUtil().setHeight(300.0),
      alignment: Alignment.center,
      margin: EdgeInsets.only(
        top: ScreenUtil().setWidth(15.0),
        bottom: ScreenUtil().setWidth(15.0),
      ),
      child: Container(
        padding: EdgeInsets.only(
            top: ScreenUtil().setWidth(30.0),
            left: ScreenUtil().setWidth(10.0),
            right: ScreenUtil().setWidth(30.0)),
        width: ScreenUtil().setWidth(690.0),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(ScreenUtil().setSp(20.0)),
            boxShadow: <BoxShadow>[
              BoxShadow(
                color: Colors.black26,
                blurRadius: ScreenUtil().setSp(10.0),
                offset: Offset(2, 2),
              )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(bottom: ScreenUtil().setWidth(20)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      ClipOval(
                        child: Image.network(
                          '${dataIndex['passenger_headimgurl']}',
                          width: ScreenUtil().setWidth(100.0),
                          height: ScreenUtil().setWidth(100.0),
                        ),
                      ),
                      SizedBox(width: ScreenUtil().setWidth(15.0)),
                      Text(
                        '${dataIndex['passenger_name']}',
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(30.0),
                          fontWeight: FontWeight.w500,
                          color: Color(0xff333333),
                        ),
                      ),
                    ],
                  ),
                  Text(
                    '${dataIndex['people_number']}人·' + typeStr,
                    style: TextStyle(
                      color: typeStr == '已付款' ||
                              typeStr == '订单完成' ||
                              typeStr == '独享' ||
                              typeStr == '拼车'
                          ? Color(0xff3FB956)
                          : Color(0xffEC674A),
                      fontSize: ScreenUtil().setWidth(28),
                    ),
                  )
                ],
              ),
            ),
            Offstage(
              offstage: !isFinish, //订单完成
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Container(
                    padding: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
                    width: ScreenUtil().setWidth(500),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.only(
                                right: ScreenUtil().setWidth(30),
                              ),
                              width: ScreenUtil().setWidth(15.0),
                              height: ScreenUtil().setWidth(15.0),
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Color(0xff00BA8F),
                              ),
                            ),
                            Expanded(
                              child: Container(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '${dataIndex['dep_are']}',
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(30.0),
                                    color: Color(0xff333333),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: ScreenUtil().setWidth(28.0)),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.only(
                                left: ScreenUtil().setWidth(0),
                                right: ScreenUtil().setWidth(30),
                              ),
                              width: ScreenUtil().setWidth(15.0),
                              height: ScreenUtil().setWidth(15.0),
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Color.fromARGB(255, 255, 102, 0),
                              ),
                            ),
                            Expanded(
                              child: Container(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '${dataIndex['dest_area']}',
                                  style: TextStyle(
                                    fontSize: ScreenUtil().setSp(30.0),
                                    color: Color(0xff333333),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  RichText(
                    text: TextSpan(
                      text: '￥',
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(28.0),
                        color: Color(0xff333333),
                      ),
                      children: <TextSpan>[
                        TextSpan(
                          text: '${dataIndex['start_cost']}',
                          style: TextStyle(
                              fontSize: ScreenUtil().setSp(36.0),
                              color: Color(0xff333333),
                              fontWeight: FontWeight.w500),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Offstage(
              offstage: isFinish, //订单进行中
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    width: ScreenUtil().setWidth(560),
                    child: Row(
                      children: [
                        Container(
                          margin: EdgeInsets.only(
                            left: ScreenUtil().setWidth(20),
                            right: ScreenUtil().setWidth(20),
                          ),
                          width: ScreenUtil().setWidth(15.0),
                          height: ScreenUtil().setWidth(15.0),
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Color(0xff3FB956),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '${dataIndex['update_time']}用车-${dataIndex['dep_are']}',
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(30.0),
                                color: Color(0xff333333),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () => Utils.callPhone(dataIndex['passenger_mobile']),
                    child: Padding(
                      padding: EdgeInsets.only(right: ScreenUtil().setWidth(5)),
                      child: Image.asset(
                        'assets/icon/passengerPone.png',
                        width: ScreenUtil().setWidth(64),
                        height: ScreenUtil().setWidth(64),
                        fit: BoxFit.cover,
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(
              height: ScreenUtil().setWidth(30),
            ),
            Offstage(
              offstage: isFinish,
              child: Divider(
                color: Color(0xffeeeeee),
                height: ScreenUtil().setWidth(1),
              ),
            ),
            Offstage(
              offstage: dataIndex['status'] == '0000',
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  InkWell(
                    onTap: () => _refuseFreeRideOrder(dataIndex),
                    child: Container(
                      padding: EdgeInsets.fromLTRB(
                        ScreenUtil().setWidth(0),
                        ScreenUtil().setWidth(30),
                        ScreenUtil().setWidth(110),
                        ScreenUtil().setWidth(30),
                      ),
                      child: Text(
                        '取消订单',
                        style: TextStyle(
                            color: Color(0xff668D6E),
                            fontSize: ScreenUtil().setWidth(30),
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                  Container(
                    color: Color(0xffeeeeee),
                    width: ScreenUtil().setWidth(1),
                    height: ScreenUtil().setWidth(73),
                  ),
                  InkWell(
                    onTap: () {
                      switch (dataIndex['status']) {
                        case '0000':
                          ToastX.center('订单已完成');
                          break;
                        case '0010':
                          if (dataIndex['pay_state'] == '0010') {
                            ToastX.center('请联系乘客支付费用');
                            return;
                          }
                          // print(dataIndex.toString());
                          CarpoolPassengerOrderInfo data =
                              CarpoolPassengerOrderInfo.fromJson(dataIndex);
                          Provider.of<OrderInformation>(context, listen: false)
                              .setCarpoolPassengerOrderInfo(data);
                          NavigatorUtil.jump(context,
                              '/carpoolPassengerMap?type=0010&first=0020');
                          break;
                        case '0020':
                          CarpoolPassengerOrderInfo data =
                              CarpoolPassengerOrderInfo.fromJson(dataIndex);
                          Provider.of<OrderInformation>(context, listen: false)
                              .setCarpoolPassengerOrderInfo(data);
                          NavigatorUtil.jump(context,
                              '/carpoolPassengerMap?type=0020&first=0020');
                          break;
                        default:
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.fromLTRB(
                        ScreenUtil().setWidth(110),
                        ScreenUtil().setWidth(30),
                        ScreenUtil().setWidth(0),
                        ScreenUtil().setWidth(30),
                      ),
                      child: Text(
                        passStyeStr,
                        style: TextStyle(
                            color: Color(0xff668D6E),
                            fontSize: ScreenUtil().setWidth(30),
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if (_tenTimer != null) {
      _tenTimer.cancel();
    }
    _tenTimer = null;
  }
}
